package com.hmdp.utils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

@Component
public class RedisIdWorker {


    private static final long BEGIN_TIMESTAMP = 1735689600L;
    private static final long COUNT_BITS = 32;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    public Long nextId(String KeyPrefix){
        //1.生成时间戳
        LocalDateTime now = LocalDateTime.now();
        long timeSecond = now.toEpochSecond(ZoneOffset.UTC);
        long timestamp = timeSecond - BEGIN_TIMESTAMP;
        //2.生成序列号
        String date = now.format(DateTimeFormatter.ofPattern("yyyy:MM:dd"));
        Long count = stringRedisTemplate.opsForValue().increment("inc:" + KeyPrefix + ":" + date);
        //3.拼接并返回
        return count << COUNT_BITS | timestamp;
    }

}
